//
//  XSJRefreshControl.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/18.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit

enum RefreshState : Int {

    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
    
}

let RefreshControlH : CGFloat = 50


class XSJRefreshControl: UIControl {

    
    private var currentScrollView : UIScrollView?
    
    private var refreshState : RefreshState = .Normal {
    
        didSet {
        
            switch refreshState {
            
            case .Normal :
                iconView.hidden = false
                messageLabel.text = "下拉刷新"
                indicatorView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.iconView.transform = CGAffineTransformIdentity
                    
                })
                
                if oldValue == .Refreshing {
                
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        self.currentScrollView?.contentInset.top -= RefreshControlH
                    
                    })
                    
                }
                
            case .Pulling:
               
                messageLabel.text = "松手就刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
               
                messageLabel.text = "正在刷新"
                iconView.hidden = true
                indicatorView.startAnimating()
                
                
                sendActionsForControlEvents(.ValueChanged)
                
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += RefreshControlH
                })
            }
        }
    }

    
    private lazy var iconView : UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var indicatorView : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    private lazy var messageLabel : UILabel = {
    
       let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
        
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setUpUI() {
    
//        backgroundColor = UIColor.redColor()
        addSubview(iconView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(iconView)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(iconView.snp_trailing)
            make.centerY.equalTo(self)
        }

        
    }
    
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else {
        
            return
            
        }
        
        
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: RefreshControlH)
        self.frame.origin.y = -RefreshControlH

        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        currentScrollView = scrollView
        
        
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if currentScrollView!.dragging {
        
            let maxY = -(currentScrollView!.contentInset.top + RefreshControlH)

            let contentOffSetY = currentScrollView?.contentOffset.y
            
            if contentOffSetY < maxY  &&  refreshState == .Normal {
            
                refreshState = .Pulling
                
            } else if contentOffSetY >= maxY && refreshState == .Pulling {
               
                refreshState = .Normal
            }
            } else {
           
            if refreshState == .Pulling {
            
                refreshState = .Refreshing
            }
           

            
        }
    }
    
    func endRefreshing() {
    
        refreshState = .Normal
        
    }
    deinit {
    
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
        
    }
    
}
